# !/usr/bin/python3
# encoding: utf-8

import os
import random
import socket
import string
import yaml
from config.logger import logger

# 固定随机数种子，支持重入执行
random.seed(socket.gethostname())

def id_generator(num):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(num))


def get_hostname(host):
    import socket
    result = socket.gethostbyaddr(host)
    return result[0].split('.')[0] if result else ""


def load_yaml(yaml_path):
    if not os.path.exists(yaml_path):
        logger.error("{} not exists. Quit...".format(yaml_path))
        exit(1)
    with open(yaml_path, "r", encoding="utf-8") as file:
        conf_map = yaml.load(file, Loader=yaml.FullLoader)
    logger.debug(f"Load vars from {yaml_path}")
    return conf_map


def dump_yaml(yaml_path, data_map, mode="w"):
    yaml.dumper.SafeDumper.ignore_aliases = lambda self, data: True
    with open(yaml_path, mode, encoding="utf-8") as file:
        yaml.dump(data_map, file, default_flow_style=False, encoding="utf-8", allow_unicode=True,
                  Dumper=yaml.dumper.SafeDumper)
    logger.debug(f"Write vars back to {yaml_path}")


def clear_file(file_path):
    logger.debug("Clear file {}".format(file_path))
    if os.path.exists(file_path):
        with open(file_path, "r+") as f:
            # 清空文件
            f.seek(0)
            f.truncate()

if __name__ == '__main__':
    print(id_generator(20))
